package com.common.service.impl;


import com.common.config.FileStorageConfig;
import com.common.exception.DownloadFileNotFoundException;
import com.common.exception.InvalidFilePathException;
import com.common.service.FileDownloadService;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.FileNotFoundException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;

/**
 * 文件下载服务实现类
 */
@Service
public class FileDownloadServiceImpl implements FileDownloadService {

    private final Path storagePath;

    public FileDownloadServiceImpl(FileStorageConfig config) {
        this.storagePath = config.fileStoragePath();
    }

    @Override
    public Resource loadFileAsResource(String fileName) {

        try {
            //安全处理文件名
            String safeFileName = StringUtils.cleanPath(fileName);
            //安全验证
            validateFileName(safeFileName);
            //获取文件路径
            Path filePath = storagePath.resolve(safeFileName).normalize();
            Resource resource = new UrlResource(filePath.toUri());//创建资源对象
            if(resource.exists() && resource.isReadable()){
                return resource;
            }else {
                throw new DownloadFileNotFoundException(safeFileName);
            }
        }catch (MalformedURLException | InvalidPathException e){
            throw new DownloadFileNotFoundException("文件路径无效: " + fileName, e);
        }
    }


    @Override
    public Path resolveFilePath(String fileName) {
        validateFileName(fileName);
        return storagePath.resolve(fileName).normalize();
    }

    private void validateFileName(String safeFileName) {
        if (safeFileName.contains("..")) {
            throw new InvalidFilePathException("非法文件名: " + safeFileName);
        }
        if(!Files.exists(storagePath.resolve(safeFileName))){
            throw new DownloadFileNotFoundException("文件未找到: " + safeFileName);
        }
    }
}
